﻿/*
 * Copyright (c) 2015-2016 Constantijn Evenhuis (blueprints@const.nl)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
using Blueprints.Resolution;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace Blueprints.Defaults
{
    /// <summary>
    /// A descriptor for a collection property that has no public set method.
    /// </summary>
    internal sealed class ReadOnlyCollectionProperty : IPropertyDescriptor
    {
        /// <summary>
        /// Creates a new CollectionReadOnlyPropertyDescriptor.
        /// </summary>
        /// <param name="propertyInfo">The property to describe.</param>
        /// <param name="descriptor">The descriptor of the collection.</param>
        public ReadOnlyCollectionProperty(PropertyInfo propertyInfo, ICollectionDescriptor descriptor)
        {
            Descriptor = descriptor;
            PropertyInfo = propertyInfo;
            Name = PropertyInfo.Name;
            ElementType = descriptor.ElementType;

            // Act as if this was a generic List<T>.
            Type = typeof(List<>).MakeGenericType(ElementType);
        }

        /// <summary>
        /// Gets the descriptor of the collection.
        /// </summary>
        public ICollectionDescriptor Descriptor
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the property this descriptor describes.
        /// </summary>
        public PropertyInfo PropertyInfo
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the name of the property.
        /// </summary>
        public string Name
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the type of elements in the collection.
        /// </summary>
        public Type ElementType
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the collection type.
        /// </summary>
        public Type Type
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the property value.
        /// </summary>
        /// <param name="instance">The object instance of which to get the property value.</param>
        /// <returns>The property value.</returns>
        public object GetValue(object instance)
        {
            IList value = (IList)Activator.CreateInstance(Type);
            object collection = PropertyInfo.GetValue(instance);
            if (collection != null)
            {
                foreach (object element in Descriptor.GetElements(collection))
                {
                    value.Add(element);
                }
            }

            return value;
        }

        /// <summary>
        /// Assigns the elements of <paramref name="value"/> to the property value.
        /// </summary>
        /// <param name="instance">The object instance of which to set the property value.</param>
        /// <param name="value">The value to set.</param>
        public void SetValue(object instance, object value)
        {
            object collection = PropertyInfo.GetValue(instance);
            if (collection == null)
            {
                throw new BlueprintException("Error adding items to the collection: value is null");
            }

            if (((IEnumerable)collection).GetEnumerator().MoveNext())
            {
                throw new BlueprintException("Error adding items to the collection: collection is not empty");
            }

            foreach (object element in (IList)value)
            {
                Descriptor.Add(collection, element);
            }
        }

        /// <summary>
        /// Gets whether the value should be serialized.
        /// </summary>
        /// <param name="instance">The object instance for which to serialize the property.</param>
        /// <param name="value">The value to serialize.</param>
        /// <returns>True if the value should be serialized, false otherwise.</returns>
        public bool ShouldSerializeValue(object instance, object value)
        {
            if (value == null)
            {
                return false;
            }

            if (((IList)value).Count == 0)
            {
                return false;
            }

            return true;
        }
    }
}